package com.mdl.mall.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Desc
 * @Author madengling
 * @Time 2020/10/26 14:50
 */
public class FileDownloadUtil {
    private static final Logger log = LoggerFactory.getLogger(FileDownloadUtil.class);
    /**
     * 下载到本地G盘
     * @param response
     * @throws MalformedURLException
     */
    public static void downloadNet(HttpServletResponse response) throws MalformedURLException {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;

        URL url = new URL("http://recept.zjzwfw.gov.cn/oss//form/4ec73f42-9218-372c-b245-01eefb11d634.jpg");

        try {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream("g:/abc.jpg");

            byte[] buffer = new byte[1204];
            int length;
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("下载完成!");
    }

    /**
     * 利用浏览器自带下载
     * 附件下载 工具方法
     * 通过附件地址获取到文件流返回给前端
     */
    public static void DownloadFj(HttpServletResponse response, String fileName, String fileUrl) {
        OutputStream out = null;
        InputStream is = null;
        try {
            response.setContentType("application/octet-stream");
            if(fileName==null || StringUtils.isEmpty(fileName)){
                String fileType = "";
                if(fileUrl.contains("?")){
                    fileType = fileUrl.substring(fileUrl.lastIndexOf(".") + 1,fileUrl.indexOf("?"));
                }else {
                    fileType = fileUrl.substring(fileUrl.lastIndexOf(".") + 1);
                }
                fileName = UUID.randomUUID().toString()+"."+fileType;
            }
            //设置附件下载的名字，如果没有设定名字，默认用UUID创建一个
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
            out = response.getOutputStream();

            CloseableHttpClient httpClient = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.DEFAULT;
            HttpGet request = new HttpGet(fileUrl);
            request.setConfig(requestConfig);
            try {
                CloseableHttpResponse httpResponse = httpClient.execute(request);
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) {
                    request.abort();
                } else {
                    HttpEntity entity = httpResponse.getEntity();
                    if (null != entity) {
                        is = entity.getContent();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                request.abort();
            }
            if (is != null) {
                int zlen = 0;
                int len = 0;
                byte[] buffer = new byte[1024 * 100];
                while ((len = is.read(buffer)) > 0) {
                    zlen = zlen + len;
                    out.write(buffer, 0, len);
                }
                out.flush();
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                if (is != null){
                    is.close();
                }
                response.flushBuffer();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param file       要上传的文件
     * @param path       上传到服务器的路径          /org/image/
     * @param userName   用户名成               张三
     * @param beifenName 备份图片时传入图片名称  如   1534554345354张三.jsp   第一次上传 为空
     * @throws Exception
     */
    public static String uploadFile(MultipartFile file, String path, String userName, String beifenName) throws Exception {
        InputStream in = null;
        OutputStream out = null;

        try {
            String dataTime = new SimpleDateFormat("yyyyMMdd").format(new Date());
            path = path + dataTime + "/";           // path :   /org/image/20200819/

            File tmpFile = new File(path);
            //判断是否存在该文件夹，若不存在则创建文件夹
            if (!tmpFile.exists()) {
                tmpFile.mkdir();
            }

            // 上传的文件名
            String uploadName = file.getOriginalFilename();         //xxxxxxxxxxxx.jpg
            log.info("uploadFile  uploadName is :{}", JSONObject.toJSONString(uploadName));
            // 获取后缀名
//        String[] strArray = uploadName.split(".");
//        int suffixIndex = strArray.length - 1;
//        String exe = strArray[suffixIndex];
            String exe = uploadName.substring(uploadName.lastIndexOf("."));
            // 组装服务器文件名
            long time = System.currentTimeMillis();
            String fileName = String.valueOf(time);//服务器保存新文件名
            if (!StringUtils.isEmpty(beifenName)) {
                fileName = beifenName.substring(beifenName.lastIndexOf("/")).replaceAll("/", "");         // 截取只要名称  20200819/144233543432张三.jpg
            } else {
                fileName = fileName + userName + exe;//文件名+后缀名     144233543432张三.jpg
            }
//        DiskFileItemFactory factory = new DiskFileItemFactory();
//        ServletFileUpload sfu = new ServletFileUpload(factory);
//        sfu.setHeaderEncoding("UTF-8"); // 处理中文问题
//        sfu.parseRequest(request); // 解码请求
            //以下是创建文件
            String filePath = path + "/" + fileName;//文件路径+文件全名                /org/image/20200819/144233543432张三.jpg
            log.info("filePathfilePathfilePath  is {} :", JSONObject.toJSONString(filePath));
            File file2 = new File(fileName);
            //若文件不存在，创建文件
            if (file2.exists()) {
                file2.createNewFile();
            }
            // 输入流
            in = file.getInputStream();
            // 输出流
            out = new FileOutputStream(filePath, true);
            //将上传文件内容，写进服务器创建的新文件。

            byte[] buffer = new byte[1024];
            while (true) {
                int byteRead = in.read(buffer);
                if (byteRead == -1) {
                    break;
                }
                out.write(buffer, 0, byteRead);
            }

            //成功返回 文件名修改后的名称
            return dataTime +"/"+ fileName;          //    20200819/144233543432张三.jpg
        } catch (MalformedURLException ex) {
            // System.err.println("写入新文件错误");
            return "error";
        } finally {
            //关闭输入流，输出流
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }

    /*
     * @MethodName: handleFileUpload
     * @Description: //TODO   文件上传方法
     * @param file
     * @param request
     * @Return: java.lang.String
     * @Exception
     * @Date: 2019/12/20 14:02
     **/
    public static String handleFileUpload(MultipartFile file, String filePath) {

        if (file.isEmpty()) {
            return "文件为空";
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        System.out.println("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        //  String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 文件上传后的路径
        //String filePath = request.getSession().getServletContext().getRealPath("") + "upload\\";
        //  System.out.println("上传的文件路径为：" + filePath + fileName);
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return filePath + fileName;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

}
